package com.example.star.view.setting;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.star.R;
import com.example.star.adapter.FeedbackAdapter;
import com.example.star.adapter.MessageAdapter;
import com.example.star.api_service.ApiFeedback;
import com.example.star.api_service.MessageApi;
import com.example.star.entity.Feedback;
import com.example.star.entity.Message;
import com.example.star.entity.Reply;
import com.example.star.entity.User;
import com.example.star.retrofit.ApiClient;
import com.example.star.view.activity.MessageActivity;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class SendReplyActivity extends AppCompatActivity {

    private EditText replyEditText;
    private Button sendReplyButton;
    private ListView feedbackListView;
    private Spinner normalUserSpinner;
    private TextView adminNameTextView;
    private String currentAdminName;
    private String selectedNormalUserName;
    private FeedbackAdapter feedbackAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_reply);

        // 从 SharedPreferences 读取用户名
        SharedPreferences sharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE);
        currentAdminName = sharedPreferences.getString("username", "");

        initViews();

        // 设置管理员名称到 TextView
        adminNameTextView.setText(currentAdminName);

        sendReplyButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendReply();
            }
        });

        getNormalUsers();
        getFeedbacks();

    }

    private void initViews() {
        replyEditText = findViewById(R.id.et_reply);
        sendReplyButton = findViewById(R.id.btn_send_reply);
        feedbackListView = findViewById(R.id.lv_feedbacks);
        normalUserSpinner = findViewById(R.id.normal_user_spinner);
        adminNameTextView = findViewById(R.id.admin_name_text_view);
    }

    private void getNormalUsers() {
        ApiFeedback apiFeedback = ApiClient.getApiFeedback();
        Call<List<User>> call = apiFeedback.getNormalUsers();
        call.enqueue(new Callback<List<User>>() {
            @Override
            public void onResponse(Call<List<User>> call, Response<List<User>> response) {
                if (response.isSuccessful()) {
                    List<User> normalUsers = response.body();
                    if (normalUsers != null) {
                        List<String> usernames = new ArrayList<>();
                        for (User user : normalUsers) {
                            usernames.add(user.getUsername());
                        }
                        ArrayAdapter<String> adapter = new ArrayAdapter<>(SendReplyActivity.this,
                                android.R.layout.simple_spinner_item, usernames);
                        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        normalUserSpinner.setAdapter(adapter);

                        normalUserSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                selectedNormalUserName = (String) parent.getItemAtPosition(position);
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> parent) {
                            }
                        });
                        Toast.makeText(SendReplyActivity.this, "获取普通用户成功", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Log.e("User", "获取普通用户失败: " + response.message() + ", 请求接口: getNormalUsers");
                    Toast.makeText(SendReplyActivity.this, "获取普通用户失败: " + response.message(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<List<User>> call, Throwable t) {
                Log.e("User", "网络请求失败: " + t.getMessage() + ", 请求接口: getNormalUsers");
                Toast.makeText(SendReplyActivity.this, "网络请求失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void sendReply() {
        String replyText = replyEditText.getText().toString();
        if (replyText.isEmpty()) {
            Toast.makeText(this, "请输入消息", Toast.LENGTH_SHORT).show();
            return;
        }

        if (selectedNormalUserName == null || selectedNormalUserName.isEmpty()) {
            Toast.makeText(this, "请选择普通用户", Toast.LENGTH_SHORT).show();
            return;
        }


        // 创建消息对象
        Reply reply = new Reply();
        reply.setAdminName(currentAdminName);
        reply.setUserName(selectedNormalUserName);



        // 这里需要根据实际情况创建 User 对象并设置到 Reply 中
        User user = new User();
        user.setUsername(selectedNormalUserName);
        reply.setUser(user);
        reply.setMessage(replyText);

        ApiFeedback apiFeedback = ApiClient.getApiFeedback();
        Call<Void> call = apiFeedback.createReply(reply);

        call.enqueue(new Callback<Void>() {
            @Override
            public void onResponse(Call<Void> call, Response<Void> response) {
                if (response.isSuccessful()) {
                    Log.d("Reply", "回复发送成功");
                    replyEditText.setText("");
                    getFeedbacks();
                    Toast.makeText(SendReplyActivity.this, "回复发送成功", Toast.LENGTH_SHORT).show();
                } else {
                    Log.e("Reply", "回复发送失败: " + response.message() + ", 请求接口: createReply");
                    Toast.makeText(SendReplyActivity.this, "回复发送失败: " + response.message(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<Void> call, Throwable t) {
                Log.e("Reply", "网络请求失败: " + t.getMessage() + ", 请求接口: createReply");
                Toast.makeText(SendReplyActivity.this, "网络请求失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void getFeedbacks() {
        ApiFeedback apiFeedback = ApiClient.getApiFeedback();
        Call<List<Feedback>> call = apiFeedback.getFeedbacksByAdminName(currentAdminName);
        call.enqueue(new Callback<List<Feedback>>() {
            @Override
            public void onResponse(Call<List<Feedback>> call, Response<List<Feedback>> response) {
                if (response.isSuccessful()) {
                    List<Feedback> feedbacks = response.body();
                    if (feedbacks != null) {
                        for (Feedback feedback : feedbacks) {
                            Log.d("Feedback", "User Name: " + feedback.getUserName());
                            Log.d("Feedback", "Message: " + feedback.getMessage());
                        }
                    }
                    feedbackAdapter = new FeedbackAdapter(SendReplyActivity.this, feedbacks);
                    feedbackListView.setAdapter(feedbackAdapter);
                } else {
                    Toast.makeText(SendReplyActivity.this, "获取消息失败: " + response.code(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<List<Feedback>> call, Throwable t) {
                Toast.makeText(SendReplyActivity.this, "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}